/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lanchat.model.net;

import com.lanchat.model.data.User;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *文件传输的UDP类
 * @author MSX008
 */
public class FileSender implements Runnable{
    private Socket socket;
    private String filename;
    public  DataInputStream fis,in;
    public  DataOutputStream out;
    public  long passedLength;
    public boolean running;

    public FileSender(User user,String file){
        try {
            this.filename=file;
            socket = new Socket(user.getAddress(), NetConstant.UDPFILEPORT);
            fis=new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
            in=new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            out=new DataOutputStream(socket.getOutputStream());
        } catch (IOException ex) {
            Logger.getLogger(FileSender.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }

    public void SendFile() throws IOException{
        File f = new File(filename);
        out.write(FileInfo.FILE_SEND);
        out.flush();
        out.writeUTF(filename);
        out.flush();
        out.writeLong((long)f.length());
        out.flush();
        if(in.read()==FileInfo.FILE_NO){
            return;
        }
        byte[] buffer=new byte[NetConstant.DATAGRAMPACKET_SIZE];
        int r=0;
        passedLength=0;
        while(running){
            if(fis!=null){
                r=fis.read(buffer);
            }
            passedLength=passedLength+r;
            if(r==-1){
                break;
            }
            out.write(buffer, 0, r);
        }
        out.flush();
        fis.close();
        socket.close();
        
    }
    @Override
    public void run() {
        try {
            running=true;
            SendFile();
        } catch (IOException ex) {
            Logger.getLogger(FileSender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void CloseSocket(){
        try {
            socket.close();
        } catch (IOException ex) {
            Logger.getLogger(FileSender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

